﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
#if EASY_MOBILE
using EasyMobile;
#endif

namespace DrawDotGame
{
    public class GameplayUIManager : MonoBehaviour
    {

        public static GameplayUIManager Instance;
        public GameManager gameManager;
        public Text heartNumber;
        public Text levelText;
        public Transform heartImg;
        public GameObject gameEndUI;
        public GameObject Win;
        public GameObject Fail;
        public GameObject btnRestart;
        public GameObject btnHint;
        public GameObject btnBack;
        //public GameObject hintAlert;
        public GameObject heartShortageAlert;
        public AnimationClip showMenuPanel;
        public AnimationClip hideMenuPanel;

        [Header("Premium Features Buttons")]
        public GameObject btnWatchRewardedAd;
        public GameObject btnInAppPurchase;

        [Header("In-App Purchase Store")]
        public GameObject storeUI;

        [Header("Sharing-Specific")]
        public GameObject shareUI;
        public ShareUIController shareUIController;

        private bool hasWatchedAd;
        private bool isFirstWin;
        private const string HINT_ALERT_PPKEY = "SGLIB_HINT_ALERT";

        public GameObject bg;
        void OnEnable()
        {
            GameManager.GameEnded += OnGameEnded;
        }

        void Awake()
        {
            Instance = this;
        }

        void OnDisable()
        {
            GameManager.GameEnded -= OnGameEnded;

        }

        // Use this for initialization
        void Start()
        {

            bg.SetActive(true);

           
            UpdateCoins();           

           
            hitClicked = true;
            gameManager.StartShowHint();
            

            gameEndUI.SetActive(false);
            levelText.text = GameManager.LevelLoaded + "";
            //btnHint.SetActive(true);
            btnRestart.SetActive(true);

            // Show or hide premium feature buttons
            //btnInAppPurchase.SetActive(PremiumFeaturesManager.Instance.enablePremiumFeatures);

            // Hidden at start
            //hintAlert.SetActive(false);
            heartShortageAlert.SetActive(false);
            storeUI.SetActive(false);
            shareUI.SetActive(false);
        }

        // Update is called once per frame
        void Update()
        {
            heartNumber.text = CoinManager.Instance.GetHeart().ToString();
            //btnWatchRewardedAd.SetActive(WJGameHelper.VideoIsReady());
        }

        void OnGameEnded(bool isWin, bool firstWin)
        {
            if (isWin)
            {
                isFirstWin = firstWin;
                Invoke("ShowUIWhenWin", 1f);
            }
            else
            {
                Invoke("ShowUIWhenGameOver", 1f);
            }
        }

        void ShowUIWhenGameOver()
        {
  
            gameEndUI.SetActive(true);
            Win.SetActive(false);
            Fail.SetActive(true);

            // Whether to show share button (premium feature)

            //Get the img and showing up
            //if (PremiumFeaturesManager.Instance.enablePremiumFeatures)
            //    ShowShareUI();
        }

        void ShowUIWhenWin()
        {
            // Award the user with hearts if needed
            if (isFirstWin && gameManager.heartsPerWin > 0)
            {
                CoinManager.Instance.AddCoins(gameManager.heartsPerWin);
                heartNumber.GetComponent<Animator>().Play("HeartIncrease");
                SoundManager.Instance.PlaySound(SoundManager.Instance.ping, true);
            }

            gameEndUI.SetActive(true);
            Win.SetActive(true);
            Fail.SetActive(false);
            

            // Whether to show share button (premium feature)

            //Get the img and showing up
            //if (PremiumFeaturesManager.Instance.enablePremiumFeatures)
            //{
            //    ShowShareUI();
            //}
        }

        public void ShowStoreUI()
        {
            Debug.Log("store ui show");
            storeUI.SetActive(true);
            storeUI.GetComponentInChildren<Animator>().Play(showMenuPanel.name);
        }

        public void HideStoreUI()
        {
            StartCoroutine(CRHideStoreUI());
        }

        IEnumerator CRHideStoreUI()
        {
            storeUI.GetComponentInChildren<Animator>().Play(hideMenuPanel.name);
            yield return new WaitForSeconds(hideMenuPanel.length);
            storeUI.SetActive(false);
        }



        public void ShowShareUI()
        {
            if (!ScreenshotSharer.Instance.disableSharing)
            {
                StartCoroutine(CR_ActiveShareUI());
            }
        }

        IEnumerator CR_ActiveShareUI()
        {
            yield return new WaitForSeconds(0.6f);
#if EASY_MOBILE_PRO
            AnimatedClip clip = ScreenshotSharer.Instance.RecordedClip;
            shareUIController.AnimClip = clip;
#endif
            Texture2D texture = ScreenshotSharer.Instance.CapturedScreenshot;
            shareUIController.ImgTex = texture;
            yield return new WaitForSeconds(0.01f);
            shareUI.SetActive(true);
        }

        public void WatchRewardedAd()
        {
            
            
        }

        public void VideoAward(int hitValue)
        {
            StartCoroutine(CRReward(hitValue));
        }

        void OnCompleteRewardedAdToEarnCoins()
        {
#if EASY_MOBILE
            // Unsubscribe
            //AdDisplayer.CompleteRewardedAdToEarnCoins -= OnCompleteRewardedAdToEarnCoins;

            // Already watch ad
            hasWatchedAd = true;

            // Give the reward!
            //StartCoroutine(CRReward(AdDisplayer.Instance.rewardedHearts));
#endif
        }

        /// <summary>
        /// 增加几次提示
        /// </summary>
        /// <param name="rewardValue"></param>
        /// <returns></returns>
        IEnumerator CRReward(int rewardValue)
        {
            Animator heartNumberAnim = heartNumber.GetComponent<Animator>();
            for (int i = 0; i < rewardValue; i++)
            {
                CoinManager.Instance.AddCoins(1);
                heartNumberAnim.Play("HeartIncrease");
                SoundManager.Instance.PlaySound(SoundManager.Instance.ping, true);
                yield return new WaitForSeconds(0.5f);
            }
        }

        public void GoToHome()
        {
            StartCoroutine(LoadScene(StringUtils.scene_Draw_FirstScene));
        }

        public void Retry()
        {
            SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        }

        public void RetryIn()
        {
            //InsAdEvaluate.instance.OnlyShowInterstitialAd();
            SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        }

        public bool hitClicked;
        public void ShowHint()
        {
            Debug.Log(GameManager.LevelLoaded);
            if (GameManager.LevelLoaded == 1)
                return;
            //if (gameManager.ShowRestartHint())
            //{
            //    if (GameManager.Instance.isStart)
            //    {
            //        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
            //        GameStates.isSecondIn = true;
            //        return;
            //    }
            //}
            //else
            //{
            //    ShowStoreUI();
            //}
            //GameManager.Instance.isStart = false;
            if (CoinManager.Instance.GetHeart() == 0)
            {
               
                    CoinManager.Instance.AddCoins(1);
                    UpdateCoins();
             
                
                return;
            }
            if (hitClicked)
                return;

            hitClicked = true;

            if (gameManager.ShowHint())
            {
                //if (PlayerPrefs.GetInt(HINT_ALERT_PPKEY, -99) == -99)
                //{
                //    // Show hint alert.
                //    hintAlert.SetActive(true);
                //    hintAlert.GetComponentInChildren<Animator>().Play(showMenuPanel.name);

                //    // Overwrite pp key.
                //    PlayerPrefs.SetInt(HINT_ALERT_PPKEY, 1);
                //}
                UpdateCoins();
                
                //if (GameManager.Instance.isStart)
                //{
                //    print("Restart/*-/*-/*/-".Colored(Colors.cyan));
                //    SceneManager.LoadScene(SceneManager.GetActiveScene().name);
                //}
                //btnHint.gameObject.SetActive(false);
            }
            else
            {
                // Not enough hearts to show hint, show message here.
                //heartShortageAlert.SetActive(true);
                //heartShortageAlert.GetComponentInChildren<Animator>().Play(showMenuPanel.name);
                ShowStoreUI();
                hitClicked = false;
            }
        }

        public void UpdateCoins()
        {
            
                if (CoinManager.Instance.GetHeart() <= 0)
                {
                    heartImg.Find("heartImg").gameObject.SetActive(false);
                    heartImg.Find("video").gameObject.SetActive(true);
                }
                else
                {
                    heartImg.Find("heartImg").gameObject.SetActive(true);
                    heartImg.Find("video").gameObject.SetActive(false);
                    
                }

            
        }

        //public void HideHintAlert()
        //{
        //    StartCoroutine(CRHideHintAlert());
        //}

        public void HideHeartShortageAlert()
        {
            StartCoroutine(CRHideHeartShortageAlert());
        }

        //IEnumerator CRHideHintAlert()
        //{
        //    hintAlert.GetComponentInChildren<Animator>().Play(hideMenuPanel.name);
        //    yield return new WaitForSeconds(hideMenuPanel.length);
        //    hintAlert.SetActive(false);
        //}

        IEnumerator CRHideHeartShortageAlert()
        {
            heartShortageAlert.GetComponentInChildren<Animator>().Play(hideMenuPanel.name);
            yield return new WaitForSeconds(hideMenuPanel.length);
            heartShortageAlert.SetActive(false);
        }

        public void NextLevel()
        {
            GameManager.LevelLoaded++;
            LevelScroller.levelSnapped = (int)((Mathf.Ceil(GameManager.LevelLoaded / (float)LevelScroller.LEVELS_PER_PACK) - 1) * LevelScroller.LEVELS_PER_PACK + 1);
            StartCoroutine(LoadScene(SceneManager.GetActiveScene().name));
        }

        IEnumerator LoadScene(string name)
        {
            yield return new WaitForSeconds(0.5f);
            SceneManager.LoadScene(name);
        }

        public void Share()
        {
            
        }

        public void ActiveBG()
        {
            bg.SetActive(false);
        }
    }
}
